from datetime import datetime, timedelta
import time

from flask import abort
from flask import current_app, jsonify
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for

from info import constants, db
from info.models import User, News, Category
from info.modules.admin import admin_blu
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET


@admin_blu.route('/news_type', methods=["GET", "POST"])
def news_type():
    """新闻分类管理"""
    # 查询分类列表

    if request.method == "GET":
        # 查询新闻分类
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/news_edit_detail.html', errmsg="查询数据错误")
        category_dict_li = []
        for category in categories:
            category_dict_li.append(category.to_dict())
        # 移除最新分类
        category_dict_li.pop(0)
        data = {
            "categories": category_dict_li
        }
        return render_template("admin/news_type.html", data=data)
    else:
        # 表示添加或者编辑分类
        # 获取参数
        name = request.json.get("name")
        # 如果id存在说明是编辑以存在的分类
        id = request.json.get("id")
        # 判断参数
        if not name:
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        if id:
            # 查询相关分类进行赋值
            try:
                id = int(id)
                category = Category.query.get(id)
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
            if not category:
                return jsonify(errno=RET.NODATA, errmsg="未查询到分类数据")
            category.name = name
        else:
            category = Category()
            category.name = name
            db.session.add(category)
        return jsonify(errno=RET.OK, errmsg="OK")


@admin_blu.route('/news_edit_detail', methods=["GET", "POST"])
def news_edit_detail():
    """新闻编辑"""
    if request.method == "GET":
        # 表示获取编辑页面
        # 获取参数  新闻id
        news_id = request.args.get("news_id")
        if not news_id:
            abort(404)
        try:
            news_id = int(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/news_edit_detail.html', errmsg="参数错误")
        # 根据新闻id 查找出新闻
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/news_edit_detail.html', errmsg="查询数据错误")
        if not news:
            return render_template('admin/news_edit_detail.html', errmsg="未查询到数据")

        # 查询新闻分类
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/news_edit_detail.html', errmsg="查询数据错误")
        category_dict_li = []
        for category in categories:
            category.to_dict()["is_selected"] = False
            if category.id == news.category_id:
                category.to_dict()["is_selected"] = True
            category_dict_li.append(category.to_dict())
        # 移除最新分类
        category_dict_li.pop(0)
        data = {
            "news": news.to_dict(),
            "categories": category_dict_li
        }
        return render_template("admin/news_edit_detail.html", data=data)

    else:
        # 获取参数
        news_id = request.form.get("news_id")
        title = request.form.get("title")
        digest = request.form.get("digest")
        content = request.form.get("content")
        index_image = request.files.get("index_image")
        category_id = request.form.get("category_id")
        # 校验参数
        if not all([news_id, title, digest, content, category_id]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
        # 查询指定id的新闻
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据查询失败")
        if not news:
            return jsonify(errno=RET.NODATA, errmsg="未查询到新闻数据")
        # 尝试读取图片
        if index_image:
            try:
                index_image = index_image.read()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
            # 将图片上传到七牛
            try:
                key = storage(index_image)
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")
            news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
        # 设置相关数据
        news.title = title
        news.digest = digest
        news.content = content
        news.category_id = category_id
        return jsonify(errno=RET.OK, errmsg="OK")


@admin_blu.route('/news_edit')
def news_edit():
    """新闻编辑页面"""
    # 获取页数
    page = request.args.get("p", 1)
    keywords = request.args.get("keywords", None)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    total_page = 1
    current_page = 1
    # 查询数据
    news_list = []
    filters = [News.status == 0]
    if keywords:
        filters.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, 10, False)
        total_page = paginate.pages
        current_page = paginate.page
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)
    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())
    # 返回
    # print(len(user_dict_li))
    data = {
        "news_list": news_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }
    return render_template("admin/news_edit.html", data=data)


@admin_blu.route('/news_review_action', methods=["POST"])
def news_review_action():
    """审核功能实现"""
    # print(888)
    # 获取参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    # 校验参数
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if action not in ["accept", "reject"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 根据id获取到当前新闻
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到数据")
    if action == "accept":
        # 表示通过
        news.status = 0
    else:
        # 表示拒绝
        # 获取拒绝原因
        reason = request.json.get("reason")
        news.status = -1
        news.reason = reason
    # 返回结果
    return jsonify(errno=RET.OK, errmsg="OK")


@admin_blu.route('/news_review_detail/<int:news_id>')
def news_review_detail(news_id):
    """点击审核后的内容页面"""
    # 根据新闻id获取到新闻
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
    if not news:
        return render_template('admin/news_review_detail.html', data={"errmsg": "未查询到此新闻"})
    data = {"news": news.to_dict()}
    return render_template("admin/news_review_detail.html", data=data)


@admin_blu.route('/news_review')
def news_review():
    """新闻审核页面"""
    # 获取页数
    page = request.args.get("page", 1)
    keywords = request.args.get("keywords", None)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    total_page = 1
    current_page = 1
    # 查询数据
    news_list = []
    filters = [News.status != 0]
    if keywords:
        filters.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, 10, False)
        total_page = paginate.pages
        current_page = paginate.page
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)
    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_review_dict())
    # 返回
    # print(len(user_dict_li))
    data = {
        "news_list": news_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }
    return render_template("admin/news_review.html", data=data)


@admin_blu.route('/user_list')
def user_list():
    """获取用户列表"""
    # 获取页数
    page = request.args.get("page", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    total_page = 1
    current_page = 1
    # 查询数据
    users = []
    try:
        paginate = User.query.filter(User.is_admin == False).paginate(page, 10, False)
        total_page = paginate.pages
        current_page = paginate.page
        users = paginate.items
    except Exception as e:
        current_app.logger.error(e)
    user_dict_li = []
    for user in users:
        user_dict_li.append(user.to_admin_dict())
    # 返回
    # print(len(user_dict_li))
    data = {
        "users": user_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }
    return render_template("admin/user_list.html", data=data)


@admin_blu.route("/user_count")
@user_login_data
def user_count():
    """用户统计"""
    # print(100)
    total_count = 0
    # 总用户量
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)
    # 用户月新增数
    mon_count = 0
    t = time.localtime()
    begin_mon_date_str = "%d-%02d-01" % (t.tm_year, t.tm_mon)
    # 将字符串转化成datetime对象
    begin_mon_date = datetime.strptime(begin_mon_date_str, "%Y-%m-%d")
    try:
        mon_count = User.query.filter(User.is_admin == False and User.create_time > begin_mon_date).count()
    except Exception as e:
        current_app.logger.error(e)
    # 用户日新增数
    day_count = 0
    begin_day_date = datetime.strptime("%d-%02d-%02d" % (t.tm_year, t.tm_mon, t.tm_mday), "%Y-%m-%d")
    try:
        day_count = User.query.filter(User.is_admin == False, User.create_time > begin_day_date).count()
    except Exception as e:
        current_app.logger.error(e)
    # 折线图数据
    active_time = []
    active_count = []
    # 获取今天的时间对象
    today_date = datetime.strptime("%d-%02d-%02d" % (t.tm_year, t.tm_mon, t.tm_mday), "%Y-%m-%d")
    for i in range(0, 31):
        # 获取某一天的0点0分
        begin_date = today_date - timedelta(days=i)
        # 获取下一天的0点0分
        end_date = today_date - timedelta(days=i-1)
        try:
            count = User.query.filter(User.is_admin == False and User.last_login > begin_date, User.last_login < end_date).count()
            active_count.append(count)
            active_time.append(begin_date.strftime('%Y-%m-%d'))
        except Exception as e:
            current_app.logger.error(e)
    active_count.reverse()
    active_time.reverse()
    data = {
        "total_count": total_count,
        "mon_count": mon_count,
        "day_count": day_count,
        "active_count": active_count,
        "active_time": active_time
    }
    return render_template("admin/user_count.html", data=data)


@admin_blu.route("/index", methods=["GET", "POST"])
@user_login_data
def index():
    user = g.user
    # print(99)
    return render_template("admin/index.html", user=user.to_dict())


@admin_blu.route("/login", methods=["GET", "POST"])
def admin_login():
    if request.method == "GET":
        # user_id = session["user_id"]
        # is_admin = session["is_admin"]
        user_id = session.get("user_id", None)
        is_admin = session.get("is_admin", False)
        if user_id and is_admin == 1:
            print(is_admin)
            return redirect(url_for("admin.index"))
        else:
            return render_template("admin/login.html")
    else:
        # 获取参数
        username = request.form.get("username")
        password = request.form.get("password")
        # 校验参数
        if not all([username, password]):
            return render_template('admin/login.html', errmsg="参数错误")
        # 查询是否有该用户及密码是否正确
        try:
            user = User.query.filter(User.nick_name == username).first()
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/login.html', errmsg="用户信息查询失败")
        if not user:
            return render_template('admin/login.html', errmsg="未查询到用户信息")
        if not user.check_passowrd(password):
            errmsg = "密码错误"
            return render_template('admin/login.html', errmsg="密码错误")
            # return jsonify(errmsg="密码错误")
        if user.is_admin == 0:
            return render_template('admin/login.html', errmsg="你还不是管理员")
        # 保存用户登陆状态
        print("=====")
        print(user.is_admin)
        session["user_id"] = user.id
        session["nick_name"] = username
        session["is_admin"] = user.is_admin
        session["mobile"] = user.mobile
        # 返回结果
        # return redirect(url_for("admin.index"))
        return redirect("http://127.0.0.1:5000/admin/index")